import {
  useGetAnimalsQuery,
  useGetBreedsQuery,
  useGetCharactersQuery,
} from "@/app/animals/animalsApi"
import AnimalCard from "@/features/AnimalCard"
import { Form } from "@/shared/ui/form"
import { useForm, useWatch } from "react-hook-form"
import sleepingDog from "@/assets/sleepingDog.png"
import { FormMultiSelect } from "@/features/form/FormMultiSelect"
import type { Option } from "@/shared/ui/fancyMultiSelect"
import { LoadingSpinner } from "@/shared/ui/loadingSpinner"

const AnimalsPage = () => {
  const form = useForm<{ breed: Option[]; character: Option[] }>({
    mode: "onChange",
    reValidateMode: "onChange",
    defaultValues: {
      character: [],
      breed: [],
    },
  })
  const values = useWatch({ control: form.control })
  const { data, isLoading } = useGetAnimalsQuery(values, {
    refetchOnMountOrArgChange: true,
  })
  const { data: breeds } = useGetBreedsQuery(null)
  const { data: characters } = useGetCharactersQuery(null)

  return (
    <div className="flex flex-col gap-6">
      <Form {...form}>
        <form onSubmit={form.handleSubmit(() => {})}>
          <div className="relative z-10 flex flex-wrap gap-x-1 gap-y-3">
            <FormMultiSelect
              control={form.control}
              name="breed"
              options={
                breeds?.map(breed => ({
                  value: String(breed.id),
                  label: breed.attributes?.name ?? "",
                })) ?? []
              }
              placeholder="Порода"
              hidePlaceholderWhenSelected
            />
            <FormMultiSelect
              control={form.control}
              name="character"
              options={
                characters?.map(character => ({
                  value: String(character.id),
                  label: character.attributes?.name ?? "",
                })) ?? []
              }
              placeholder="Характер"
              hidePlaceholderWhenSelected
            />
          </div>
        </form>
      </Form>
      {!isLoading ? (
        <div className="flex flex-col gap-4">
          {data?.length ? (
            data?.map(({ id, attributes }) => (
              <AnimalCard key={id} {...attributes} id={id} type="search" />
            ))
          ) : (
            <div className="flex-1 flex flex-col items-center h-full justify-center">
              <h2 className="text-2xl">Ничего не найдено</h2>
              <img
                className="w-[220px] h-[220px] object-contain"
                src={sleepingDog}
                alt=""
              />
            </div>
          )}
        </div>
      ) : (
        <div className="flex justify-center items-center w-full h-full min-h-12">
          <LoadingSpinner />
        </div>
      )}
    </div>
  )
}
export default AnimalsPage
